package cn.devcat.sso.util;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.devcat.sso.config.exception.DevcatAuthException;
import cn.devcat.sso.config.exception.DevcatUserException;
import cn.devcat.sso.config.security.SecurityMessageUtil;
import cn.devcat.sso.entity.DevcatUser;
import cn.devcat.sso.service.IDevcatUserService;

@Component
public class UserUtil {

	@Autowired
	RedisUtil redisUtil;
	
	@Autowired
	IDevcatUserService userService;
	
	public DevcatUser getUserByRequest() throws DevcatAuthException {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		String uuid = request.getHeader(HttpHeaders.AUTHORIZATION);
		if(redisUtil.checkKey(uuid)) {
			String token = redisUtil.select(uuid);
			String username = JWTUtil.decode(token).getClaim("username").asString();
			return userService.getUserByUsername(username);
		}else {
			throw new DevcatAuthException(SecurityMessageUtil.NO_LOGIN);
		}
	}
	
	/**
	 * 更具出生年月计算年龄
	 * @param birthday 生日
	 * @return 年龄
	 * @throws DevcatUserException 异常信息
	 */
	public int getAge(LocalDate birthday) throws DevcatUserException {
		LocalDate currentDate = LocalDate.now();
		if(currentDate.isBefore(birthday)) {
			throw new DevcatUserException("您设置的日期大于当前日期，设置失败");
		}
		return (int)ChronoUnit.YEARS.between(birthday, currentDate);
	}
}
